//
//  NXScrollSegementView.m
//  NXScrollPageView
//
//  Created by N-X on 2018/3/24.
//  Copyright © 2018年 MRNAN. All rights reserved.
//

#import "NXScrollSegementView.h"
#import "NXSegementTitleStyle.h"
#import "UIView+NXSize.h"

@interface NXScrollSegementView()
// 缓存标题labels
@property (nonatomic ,strong)NSMutableArray * labelsArray;
// 缓存所有标题的宽度，达到根据文字去自适应宽度
@property (nonatomic ,strong)NSMutableArray * labelWidthArray;
// 所有的标题
@property (nonatomic ,strong)NSArray * titles;
// 管理标题的滚动
@property (nonatomic ,strong)UIScrollView  * scrollView;
// 底部的滚动条
@property (nonatomic ,strong)UIView * scrollLine;
@property(nonatomic,assign)NSInteger currentIndex;

@end

@implementation NXScrollSegementView

- (instancetype)init
{
    return [self initWithFrame:CGRectZero] ;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    NXSegementTitleStyle * style = [[NXSegementTitleStyle alloc]init];
    return [self initWithFrame:frame andTitles:nil segementStyle:style];
}
- (instancetype)initWithFrame:(CGRect)frame andTitles:(NSArray *)titles segementStyle:(NXSegementTitleStyle *)segementStyle
{
    if (self = [super initWithFrame:frame]) {
        _titles = titles;
        _titleStyle = segementStyle;
        _currentIndex = 0;
        [self addSubview:self.scrollView];
        [self setUpTitles];
    }
    return self;
}

#pragma mark - lazy load

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.scrollsToTop = NO;
        scrollView.bounces = self.titleStyle.isSegmentViewBounces;
        scrollView.pagingEnabled = NO;
//        scrollView.delegate = self;
        _scrollView = scrollView;
    }
    return _scrollView;
}

- (NSMutableArray *)labelWidthArray
{
    if (!_labelWidthArray) {
        _labelWidthArray = [NSMutableArray array];
    }
    return _labelWidthArray;
}

- (NSMutableArray *)labelsArray
{
    if (!_labelsArray) {
        _labelsArray = [NSMutableArray array];
    }
    return _labelsArray;
}

- (UIView *)scrollLine
{
    if (!self.titleStyle.isScrollLine) {
        return nil;
    }
    
    if (!_scrollLine) {
        _scrollLine = [[UIView alloc]init];
        _scrollLine.backgroundColor = self.titleStyle.scrollLineColor;
    }
    return _scrollLine;
}

#pragma mark - private method

- (void)setUpTitles
{
    [self.titles enumerateObjectsUsingBlock:^(NSString *  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
        UILabel * label  = [[UILabel alloc]initWithFrame:CGRectZero];
        label.tag = idx;
        label.text = title;
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = self.titleStyle.normalTitleColor;
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleLabelOnClick:)];
        [label addGestureRecognizer:tap];
        CGSize  titleSize = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0)        options:NSStringDrawingUsesLineFragmentOrigin
            attributes:@{NSFontAttributeName:label.font}
            context:nil].size;
        
        [self.labelWidthArray addObject:@(titleSize.width)];
        [self.labelsArray addObject:label];
        [self.scrollView addSubview:label];
    }];
    
    UILabel * currentLabel = self.labelsArray[_currentIndex];
    currentLabel.textColor = self.titleStyle.selectedTitleColor;
    
    [self layoutTitleLabels];
}

- (void)layoutTitleLabels
{
    [self.labelsArray enumerateObjectsUsingBlock:^(UILabel  * _Nonnull  label, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat labelWidth = [self.labelWidthArray[idx] floatValue];
        CGFloat labelY = 0;
        CGFloat labelX = self.titleStyle.margin;
        CGFloat labelH = self.bounds.size.height;
        if (idx != 0) {
            UILabel * forgroundLabel = self.labelsArray[idx - 1];
            labelX = CGRectGetMaxX(forgroundLabel.frame) + self.titleStyle.margin;
        }
        label.frame = CGRectMake(labelX, labelY, labelWidth, labelH);
    }];
    //设置contentSize
    UILabel * lastLabel = self.labelsArray.lastObject;
    self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(lastLabel.frame) + self.titleStyle.margin, 0);
    self.scrollView.frame = self.bounds;
    UILabel * forgroundLabel = self.labelsArray.firstObject;
    self.scrollLine.frame = CGRectMake(CGRectGetMinX(forgroundLabel.frame), self.scrollView.nx_height - self.titleStyle.scrollLineHeight, forgroundLabel.nx_width, self.titleStyle.scrollLineHeight);
    [self.scrollView addSubview:self.scrollLine];
}

#pragma mark - public method

- (void)adjustUIWithProgress:(CGFloat)progress fromImdex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex
{
    
    UILabel * fromLabel = self.labelsArray[fromIndex];
    UILabel * toLabel = self.labelsArray[toIndex];
    
    CGFloat xDistance = toLabel.frame.origin.x - fromLabel.frame.origin.x;
    CGFloat wDistance = toLabel.frame.size.width - fromLabel.frame.size.width;
    self.scrollLine.nx_x = fromLabel.nx_x + xDistance * progress;
    self.scrollLine.nx_width = fromLabel.nx_width + wDistance * progress;
}

- (void)adjustTitleLabelWithIndex:(NSInteger)index
{
    UILabel * currentLabel = self.labelsArray[index];
    CGFloat distance = currentLabel.center.x - self.frame.size.width * 0.5;
    if (distance < 0 || distance > self.scrollView.contentOffset.x > self.scrollView.contentSize.width - self.frame.size.width) {
        distance = 0;
    }
    [self.scrollView setContentOffset:CGPointMake(distance, 0) animated:YES];
    
    currentLabel.textColor = self.titleStyle.selectedTitleColor;
    NSInteger selectedIndex = 0;
    for (UILabel * label in self.labelsArray) {
        if (selectedIndex != index) {
            label.textColor = self.titleStyle.normalTitleColor;
        }
        selectedIndex ++;
    }
}

#pragma mark - 点击事件处理

- (void)titleLabelOnClick:(UIGestureRecognizer *)gusture
{
    UILabel * label = (UILabel *)gusture.view;
    NSInteger index = label.tag;
    !self.titleLabelClickBlock?:self.titleLabelClickBlock(index);
    [self adjustTitleLabelWithIndex:index];
}

@end
